<?php

namespace App\Libraries\Common;

use Pinq\Traversable;

trait PinqHelper
{
    protected function Pagelist($is_web, Traversable $current_data)
    {
        $request = request()->all();
        $pageSize = $request['limit'] ?? 15;
        $currPage = $request['page'] ?? 1;
        $data = $this->getPageData($current_data);
        $data = $this->collectToArray($data);
        if ($is_web) {
            $result = [
                    'code' => 0,
                    'msg' => '正在请求中...',
                    'count' => $current_data->count(),
                    'data' => $data,
                ];
        } else {
            $result = [
                'data' => $data,
                'meta' => [
                    'total' => $current_data->count(),
                    'count' => $pageSize,
                    'per_page' => $pageSize,
                    'current_page' => $currPage,
                    'total_page' => ceil($current_data->count() / $pageSize),
                ],
            ];
        }

        return $result;
    }

    protected function getResultData($is_web, Traversable $current_data, $data)
    {
        $request = request()->all();
        $pageSize = $request['limit'] ?? 15;
        $currPage = $request['page'] ?? 1;
        if ($is_web) {
            $result = [
                    'code' => 0,
                    'msg' => '正在请求中...',
                    'count' => $current_data->count(),
                    'data' => $data,
                ];
        } else {
            $result = [
                'data' => $data,
                'meta' => [
                    'total' => $current_data->count(),
                    'count' => $pageSize,
                    'per_page' => $pageSize,
                    'current_page' => $currPage,
                    'total_page' => ceil($current_data->count() / $pageSize),
                ],
            ];
        }

        return $result;
    }

    protected function getPageData(Traversable $current_data)
    {
        $request = request()->all();
        $pageSize = $request['limit'] ?? 15;
        $currPage = $request['page'] ?? 1;
        $data = $current_data->take($pageSize * $currPage)->skip($pageSize * ($currPage - 1))->asArray();

        return $data;
    }

    public function collectToArray($data)
    {
        $collection = collect($data);

        return $collection->flatten(1);
    }

    public function DataList($is_web, Traversable $current_data)
    {
        if ($is_web) {
            $result = [
                'code' => 0,
                'msg' => '正在请求中...',
                'count' => $current_data->count(),
                'data' => $this->collectToArray($current_data),
            ];
        } else {
            $result = $this->collectToArray($current_data);
        }

        return $result;
    }
}
